package tagdb.ui;


import org.apache.log4j.Appender;
import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;

import javax.swing.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.io.Writer;

/**
 * <b>Log Panel</b>
 * <p/>
 * <p>
 * This class displays LogEvents in a {@link JPanel}.
 * </p>
 *
 * @author T.Muth
 */
public class LogPanel extends JPanel {
    private static final int MAXLINES = 1000;
    private JScrollPane panel = new JScrollPane();
    private JTextArea textArea = new JTextArea();
    private LogWriter writer;
    private WriterAppender appender;

    public LogPanel(boolean useWriter) {
        super();
        // configure panel
        this.setLayout(new BorderLayout());
        textArea.setEditable(false);
        textArea.setFont(new Font("Courier", textArea.getFont().getStyle(), 12));
        textArea.setBackground(Color.WHITE);
        panel.getViewport().add(textArea, null);
        panel.setBorder(null);
        this.add(panel, BorderLayout.CENTER);

        // configure local log
        if (useWriter) {
            writer = new LogWriter(this);
            appender = new WriterAppender(new PatternLayout("%m%n"), writer);
            BasicConfigurator.configure(appender);
        }
    }

    public Appender getAppender() {
        return appender;
    }

    public void append(String str) {
        // append string
        textArea.append(str);

        // check line count
        int lines = textArea.getLineCount();
        if (lines > MAXLINES) {
            try {
                textArea.getDocument().remove(0, lines - MAXLINES);
            } catch (BadLocationException exception) {
                exception.printStackTrace();
            }
        }

        // scroll down
        Point point = new Point(0, textArea.getSize().height);
        JViewport port = panel.getViewport();
        port.setViewPosition(point);
    }

    private class LogWriter extends Writer {

        private LogPanel logpanel;

        public LogWriter(LogPanel logframe) {
            this.logpanel = logframe;
        }

        public void close() throws java.io.IOException {

        }

        public void flush() throws java.io.IOException {

        }

        public void write(final String str) {
            SwingUtilities.invokeLater(new Runnable() {

                public void run() {
                    logpanel.append(str);
                }
            });
        }

        public void write(char[] parm1, int parm2, int parm3) throws java.io.IOException {
            write(String.valueOf(parm1, parm2, parm3));
        }
    }

}

